"""
The entity object is a single in-game object.
"""
from component import cfactory, component
from pickle import load, dump
from uuid import uuid4

class entity(object):
    name = "A nondescript object."
    short = "A nondescript object lies here."
    description = "A non descript object, void of any color or features."
    location = None
    uid = 0
    vnum = 0
    def __init__(self):
        self.components = []
        self.contents = []
        self.uid = uuid4().int
    def serialize(self, path):
        """
        Called to serialize the data to a specified file.
        """
        output = open(path, "w")
        dump(self, output)
        output.close()

    @staticmethod
    def deserialize(path):
        """
        Called to read the data back into the object from the specified id.
        returns the newly created object.
        """
        inp = open(path, "r")
        obj = load(inp)
        inp.close()
        return obj

    #component management methods
    def attachComponent(self, name):
        """
        Locates the requested component from the factory and attaches it to the object.
        Also checks for dependencies.
        """

        dependencies = []
        component.calculateDependencies(name, dependencies)
        for componentname in dependencies:
            comp = cfactory.get(componentname)
            instance = (comp)()
            self.components.append(instance)
            instance.onAttach(self)

    def getComponent(self, name):
        """
        Locates and returns the component in the list of components.
        """

        for com in self.components:
            if com._name == name:
                return com

        return None

    def calculateDependencies(self):
        """
        Calculates the dependencies for all components on the object.
        """

        for com in self.components:
            deps = []
            for dep in component.calculateDependencies(com, deps):
                self.attachComponent(dep)
